<?php
function mobile_service_distributor_list($parameters)
{
    global $user;
    $start = $parameters['page_count'] * variable_get("list_page_item_number", 5);

    $query = db_select('addr', 'A');//地址表
    $query->join('distributor', 'D', 'A.addr_id=D.addr_id');//内连接 成一个表
    $query->fields('D');
    if(!user_access('view all distributor') && user_access('view own distributor')){
        $query->condition('D.author_uid',$user->uid, '=');
    }
    //地址级别查询
    if (!empty($parameters['county'])) {//县级
        $query->condition('A.county_id', $parameters['county'], '=');
    } elseif (!empty($parameters['city'])) {//市级
        $query->condition('A.city_id', $parameters['city'], '=');
    } elseif (!empty($parameters['province'])) {//省级
        $query->condition('A.province_id', $parameters['province'], '=');
    }
    //模糊条件筛选
    if (!empty($parameters['telephone'])) {//模糊地址查询条件
        $query->condition('D.cell', db_like($parameters['telephone']) . '%', 'LIKE');
    }
    if (!empty($parameters['distributor_name'])) {
        $query->condition('D.distributor_name', '%'.db_like($parameters['distributor_name']) . '%', 'LIKE');
    }

    $query->leftJoin('addr', 'A1', 'A.province_id=A1.addr_id');
    $query->leftJoin('addr', 'A2', 'A.city_id=A2.addr_id');
    $query->leftJoin('addr', 'A3', 'A.county_id=A3.addr_id');
    $query->addField('A1', 'name', 'province');
    $query->addField('A2', 'name', 'city');
    $query->addField('A3', 'name', 'county');
    $query->orderBy('D.timestamp', 'DESC');

    $query->range($start, variable_get("list_page_item_number", 5));
    $results = $query->execute();
    foreach ($results as $result) {
        $distributors[] = $result;
    }
    $object_distributors = (object)["data" => $distributors];
    return $object_distributors;
}
function distributor_add_validate( &$parameters) {
    $validata_error = '';
    if(isset($parameters['distributor_id']) && empty($parameters['distributor_id'])) {
        if (isset($parameters['account'])&&!empty($parameters['account'])) {
            if ($error = user_validate_name($parameters['account'])) {
                $validata_error = $error;
            }
            elseif ((bool) db_select('users')->fields('users', array('uid'))->condition('name', db_like($parameters['account']), 'LIKE')->range(0, 1)->execute()->fetchField()) {
                $validata_error .= '用户名 '.$parameters['account'] .'已存在.' ;
            }
        }

        if (empty($parameters['account'])) {
            $record = db_select('users', 'u')
                ->condition('u.name', $parameters['cell'])
                ->fields('u')
                ->execute()->fetchAssoc();
            if (!empty($record)) {
                $validata_error .= '利用该手机号作为登录名，该手机号已存在！';
            }
        }

    }
    return $validata_error;
}

function mobile_service_distributor_add($parameters)
{
    $validate_result = distributor_add_validate($parameters);

    if(!empty($validate_result)){
        $result_option = (object)["option" => 0,"error"=>$validate_result];
        return $result_option;
    }
    global $user;
    $id = $parameters['distributor_id'];
    $address = $parameters['addr_id'];
    if ($parameters['parent_distributor_id'] != "0") { // to-do: 考虑上级经销商修改/删除情况，会影响下级所有经销商level和parent字段
        $parent = distributor_load($parameters['parent_distributor_id']);
        $level = $parent->level + 1;
    } else {
        $level = 1;
    }
    $transaction = db_transaction();
    try {
        $role_result = user_role_load_by_name('经销商');
        if (empty($id)) { //add new distributor
            $new_user = array(
                'name' => !empty($parameters['account']) ? $parameters['account'] : $parameters['cell'],
                'pass' =>  '123456',
                'mail' => $parameters['email'],
                'signature_format' => 'filtered_html',
                'status' => 1,
                'language' => 'zh-hans',
                'timezone' => 'Asia/Shanghai',
                'init' => $parameters['email'],
                'roles' => array(
                    $role_result->rid =>  '经销商',
                ),
            );


            $account = user_save('', $new_user);
            $nid = db_insert('distributor')// Table name no longer needs {}
            ->fields(array(
                'addr_id' => $address,
                'distributor_id' => $account->uid,
                'distributor_name' => $parameters['distributor_name'],
                'parent_distributor_id' => $parameters['parent_distributor_id'],
                'level' => $level,
                'addr_details' => $parameters['addr_details'],
                'inorout' => $parameters['inorout'],
                'phone' => $parameters['phone'],
                'cell' => $parameters['cell'],
                'email' => $parameters['email'],
                'comments' => $parameters['comments'],
                'author_uid' => $user->uid,
                'timestamp' => time(),))
                ->execute();
            $result_option = (object)["option" => 1];
            return $result_option;
        } else {
            $account = user_load($id);
            $new_user = array(
                'mail' => $parameters['email'],
                'signature_format' => 'filtered_html',
                'status' => 1,
                'language' => 'zh-hans',
                'timezone' => 'Asia/Shanghai',
                'init' => $parameters['email'],
                'roles' => array(
                    $role_result->rid =>  '经销商',
                ),
            );
            user_save($account, $new_user);

            $nid = db_update('distributor')// edit exsting store. todo: update only modified fields
            ->fields(array(
                'addr_id' => $address,
                'distributor_name' => $parameters['distributor_name'],
                'parent_distributor_id' => $parameters['parent_distributor_id'],
                'level' => $level,
                'addr_details' => $parameters['addr_details'],
                'inorout' => $parameters['inorout'],
                'phone' => $parameters['phone'],
                'cell' => $parameters['cell'],
                'email' => $parameters['email'],
                'comments' => $parameters['comments'],
                'author_uid' => $user->uid,
                'timestamp' => time(),))
                ->condition('distributor_id', $id, '=')
                ->execute();
            $result_option = (object)["option" => 1];
            return $result_option;
        }
    }catch (Exception $e) {
        $transaction->rollback();
        $result_option = (object)["option" => 0,"error"=>$e->getMessage()];
        return $result_option;
    }
}
function distributor_load($id) {
    $result = db_select('distributor', 'P')
        -> fields('P')
        -> condition('P.distributor_id',$id, '=')
        -> execute()
        -> fetchObject();
    return $result;
}